/*
 * 天虹商场股份有限公司版权所有.
 */
package com.rainbow.formework.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

/**
 * TODO
 *
 * @author 黄明坤
 * @version 1.0.0
 * @date 2020/7/3
 */
public class HMKAopProxyUtils {

    /**
     * 获取代理
     * @param proxy
     * @return
     */
    public static Object getTargetObject(Object proxy) throws Exception {
        //如果不是一个代理对象，就直接返回
        if(!isAopProxy(proxy)){
            return proxy;
        }else{
            //是代理对象获取被代理的对象
            return getProxyTargetObject(proxy);
        }
    }

    /**
     * 获取代理类的目标对象
     * @param proxy
     * @return
     * @throws Exception
     */
    private static Object getProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        HMKAopProxy aopProxy = (HMKAopProxy) h.get(proxy);
        Field target = aopProxy.getClass().getDeclaredField("target");
        target.setAccessible(true);
        return target.get(aopProxy);
    }

    private static boolean isAopProxy(Object proxy) {
        return Proxy.isProxyClass(proxy.getClass());
    }
}
